import { getBase64 } from '@/utils/format';
import {
  ModalForm,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { Image, message } from 'antd';
import { openDB } from 'idb';
import { cloneDeep } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

// 初始化 IndexedDB
const dbPromise = openDB('ImageStorage', 1, {
  upgrade(db) {
    db.createObjectStore('dataSource');
  },
});

const AddAndEdit = ({
  open,
  setOpen,
  isEdit,
  record,
  dataSource,
  callback,
}) => {
  const [type, setType] = useState(1);
  const [previewImageUrl, setPreviewImageUrl] = useState('');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    // 组件加载时从 IndexedDB 获取文件列表
    // loadFilesFromCache();
  }, []);

  const loadFilesFromCache = async () => {
    const db = await dbPromise;
    const cachedFiles = await db.getAll('dataSource');
    console.log(666666, cachedFiles);
  };

  // 移除
  const handleRemove = async (file) => {
    try {
      const db = await dbPromise;
      await db.delete('dataSource', id);
      // setFileList((prev) => prev.filter((item) => item.uid !== file.uid));
      message.success('文件已从缓存中删除');
    } catch (error) {
      console.error('文件删除失败:', error);
      message.error('文件删除失败');
    }
  };

  useEffect(() => {
    if (isEdit && open) {
      initData();
    }
    if (!open) {
      setType(1);
    }
  }, [open]);

  const initData = () => {
    formRef.current?.setFieldsValue({
      title: record.title,
      // url: record.url,
      linkOrLocal: record.linkOrLocal,
      link: record.link,
      url: [
        {
          uid: record.id,
          name: record.id,
          status: 'done',
          url: record.url,
          originFileObj: record.url,
        },
      ],
      dec: record.dec,
    });
    setType(record.linkOrLocal);
  };

  /** 图片查看 */
  const previewImage = () => {
    return (
      <Image
        src={''}
        preview={{
          visible: previewVisible,
          src: previewImageUrl,
          onVisibleChange: (value) => {
            setPreviewImageUrl('');
            setPreviewVisible(false);
          },
        }}
      />
    );
  };

  const formRef = useRef();
  return (
    <div>
      <ModalForm
        layout="horizontal"
        width={600}
        colProps={{ span: 24 }}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        formRef={formRef}
        open={open}
        modalProps={{
          destroyOnClose: true,
          forceRender: true,
          onCancel: () => {
            setOpen(false);
          },
        }}
        title={isEdit ? '编辑图片' : '新增图片'}
        onOpenChange={setOpen}
        style={{ paddingTop: 20 }}
        onFinish={async (value) => {
          const newValue = cloneDeep(value);
          let obj = {};

          //处理数据
          obj['title'] = newValue.title;
          obj['dec'] = newValue.dec;
          obj['linkOrLocal'] = newValue.linkOrLocal;
          if (newValue.linkOrLocal === 1) {
            //附件上传
            obj.urlSmall = newValue.url[0].thumbUrl;
            try {
              let urlOld = await getBase64(newValue.url[0].originFileObj);
              obj.url = urlOld;
            } catch (error) {
              let urlOld = newValue.url[0].originFileObj;
              obj.url = urlOld;
            }
            //原图
          } else {
            // 链接上传
            obj.link = newValue.link;
          }
          let id = uuidv4();
          if (isEdit) {
            obj['id'] = record.id;
            // 更新数据
            const db = await dbPromise;
            await db.put('dataSource', obj, record.id);
          } else {
            obj.id = id;
            console.log(888, obj);
            const db = await dbPromise;
            await db.add('dataSource', obj, id);
          }
          setOpen(false);
          callback();
        }}
      >
        <ProFormText
          name="id"
          label="ID"
          value={isEdit ? record.id : uuidv4()}
          disabled
        />
        <ProFormText
          name="title"
          label="标题"
          placeholder="请输入标题"
          rules={[
            { required: true, message: '标题是必填项' },
            {
              pattern: /^\S+(\s+\S+)*$/,
              message: '不能以空格开始或结束',
            },
          ]}
        />
        <ProFormTextArea
          name="dec"
          label="描述"
          fieldProps={{
            autoSize: { minRows: 2, maxRows: 6 },
          }}
          placeholder="请输入描述"
          rules={[
            { required: true, message: '描述是必填项' },
            {
              pattern: /^\S+(\s+\S+)*$/,
              message: '不能以空格开始或结束',
            },
          ]}
        />
        <ProFormRadio.Group
          label="本地或链接"
          name="linkOrLocal"
          initialValue={1}
          options={[
            { label: '本地', value: 1 },
            { label: '链接', value: 2 },
          ]}
          fieldProps={{
            onChange: (e) => {
              setType(e.target.value);
            },
          }}
        />
        {type === 1 && (
          <ProFormUploadButton
            name="url"
            label="门头照"
            max={1}
            // fileList={fileList}
            fieldProps={{
              accept: 'image/png, image/jpeg',
              name: 'file',
              listType: 'picture-card',
              beforeUpload: (file) => {
                if (file.size / 1024 / 1024 > 20) {
                  message.error('照片大小超过5M');
                }
                return file.size / 1024 / 1024 <= 20;
              },
              onPreview: async (file) => {
                const src = file.url || (await getBase64(file.originFileObj));
                if (src) {
                  setPreviewImageUrl(src || '');
                  setPreviewVisible(true);
                }
              },
            }}
            title={'上传图片'}
            rules={[
              {
                required: true,
                validator: (rule, value) => {
                  const typeList = ['png', 'jpg'];
                  let flag = false;
                  let typeFlag = false;
                  flag = value?.some((v) => v.size / 1024 / 1024 > 20);
                  typeFlag = value?.some(
                    (v) => !typeList.includes(v.url?.split('.').pop()),
                  );
                  if (!value || value.length === 0) {
                    return Promise.reject('图片是必填项');
                  }
                  if (value.length > 0 && flag) {
                    return Promise.reject('照片大小超过5M');
                  }
                  return Promise.resolve();
                },
              },
            ]}
            action="/upload.do"
            extra={'支持格式：.jpg .png，单个文件不能超过5MB'}
          />
        )}
        {type === 2 && (
          <ProFormTextArea
            name="link"
            label="图片地址"
            fieldProps={{
              autoSize: { minRows: 2, maxRows: 6 },
            }}
            placeholder="请输入转换后的图片地址"
            rules={[
              { required: true, message: '图片地址是必填项' },
              {
                pattern: /^\S+(\s+\S+)*$/,
                message: '不能以空格开始或结束',
              },
            ]}
          />
        )}
      </ModalForm>
      {previewImage()}
    </div>
  );
};

export default AddAndEdit;
